package com.cmsky.open.core.tool;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.tools.view.context.ViewContext;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

public abstract class VelocityTool {
	protected static final String DATE_FORMAT = "yyyy-MM-dd";
	
	protected static final String TIME_FORMAT = "HH:mm:ss";
	
	protected static final String DATE_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss";
	
	protected static final String TIMESTAMP_FORMAT = "yyyy-MM-dd HH:mm:ss.S";
	
	protected static final String LIGERUI_FORMAT = "yyyy-MM-dd HH:mm";
	
	protected HttpServletRequest request;
	protected HttpServletResponse response;
	protected ServletContext context;
	protected VelocityContext velocity;
	protected VelocityEngine engine;
	protected WebApplicationContext ctx = null;

	abstract public void initSelf();

	/*
	 * Initialize toolbox
	 * 
	 * @see org.apache.velocity.tools.view.tools.ViewTool#init(java.lang.Object)
	 */
	public void init(Object obj) {
		if (obj instanceof ViewContext) {
			ViewContext viewContext = (ViewContext) obj;
			request = viewContext.getRequest();
			response = viewContext.getResponse();
			context = viewContext.getServletContext();
			velocity = (VelocityContext) viewContext.getVelocityContext();
			engine = viewContext.getVelocityEngine();
			ctx = WebApplicationContextUtils
					.getWebApplicationContext(this.context);
		}
		// scope: application
		else if (obj instanceof ServletContext) {
			context = (ServletContext) obj;
			ctx = WebApplicationContextUtils
					.getWebApplicationContext(this.context);
		} else if (obj instanceof WebApplicationContext) {
			ctx = (WebApplicationContext) obj;
		}
		initSelf();
	}
	
	public static String get_LIGERUI_FORMAT(){
		return LIGERUI_FORMAT;
	}
}
